package org.example.functionInterface;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class AsyncToSyncExample {
    // 假设有一个方法用于向MQ发送消息并返回一个CompletableFuture
    public static CompletableFuture<String> sendMessageToMQ(String message) {
        // 模拟异步发送消息到MQ
        return CompletableFuture.supplyAsync(() -> {
            // 模拟处理时间
            try {
                Thread.sleep(3000); // 假设处理需要3秒钟
            } catch (InterruptedException e) {
                throw new RuntimeException("Interrupted while processing message", e);
            }
            // 模拟处理结果
            return "Processed result: " + message;
        });
    }

    // 控制器方法，异步发送消息并同步返回处理结果
    public static String controllerMethod(String inputMessage) throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = sendMessageToMQ(inputMessage);
        // 使用CompletableFuture的get方法阻塞等待结果
        return future.get();
    }

    public static void main(String[] args) throws Exception {
        String result = controllerMethod("Hello MQ");
        System.out.println("Result: " + result);
    }
}